package com.itheima.health.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 */
@Component
public class AliOSSUtils {
    /**
     * 阿里云OSS相关配置信息
     */
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5t8HaX5sLk5yB1RrS7na";
    private String accessKeySecret = "4DpQoYaU3bXjc1XTijpWxqVsXoUzam";
    private String bucketName = "hmleadnews8624";

    /**
     * 上传文件到阿里云OSS
     */
    public String upload(MultipartFile file) throws IOException {
        //获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到阿里云OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        //关闭oss客户端
        ossClient.shutdown();
        return url;
    }

    /**
     * 删除文件
     */
    public void delete(String fileName) {
        String baseUrl = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] +"/";

        if (fileName.startsWith(baseUrl)) {
            //提取分隔符后的部分
            fileName = fileName.substring(baseUrl.length());
        } else {
            //处理URL不匹配的情况
            throw new IllegalArgumentException("文件路径不匹配");
        }
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //删除文件
        ossClient.deleteObject(bucketName, fileName);

        //关闭OSSClient
        ossClient.shutdown();
    }
}
